package com.example.administrator.energyida.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.example.administrator.energyida.R;
import com.example.administrator.energyida.fragment.PersonalFragment;
import com.example.administrator.energyida.util.OceanUtil;
import com.jaeger.library.StatusBarUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class FormMapActivity extends Activity {

    private MapView mMapView;
    private AMap aMap;
    private Marker factoryMarker;
    private Button buttonSubmit;

    private String email;
    private String factoryName;
    private String factoryPhone;
    private String factoryCharge;
    private double companyPointLat;
    private double companyPointLong;
    private double factoryPointLat;
    private double factoryPointLong;
    private String companyName;
    private String companyPhone;
    private String useWater;
    private String useElectricity;
    private String useGas;
    private String useHeat;
    private String oldName;
    private boolean reset;

    private String response;
    private Handler handler;

    private ArrayList<HashMap<String, String>> listFactory = new ArrayList<>();
    private ArrayList<ArrayList<HashMap<String, String>>> listFarm = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_form_map);

        // 设置状态栏的颜色
        StatusBarUtil.setColor(this, Color.parseColor("#10cafd"), 50);


        initViews();
        mMapView.onCreate(savedInstanceState);// 此方法必须重写
        initHandler();

        LatLng latLngCenter = new LatLng(companyPointLat,companyPointLong);//构造一个位置
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter,17));

        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {

                LatLng latLngCompany = new LatLng(companyPointLat, companyPointLong);
                final Marker marker = aMap.addMarker(new MarkerOptions().position(latLngCompany).title(companyName));
                marker.showInfoWindow();
            }
        });

        aMap.setOnMapLongClickListener(new AMap.OnMapLongClickListener() {
            @Override
            public void onMapLongClick(LatLng latLng) {
                aMap.clear();
                factoryMarker = aMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(),R.drawable.ic_location))));
                LatLng latLngLibrary = new LatLng(companyPointLat, companyPointLong);
                Marker marker = aMap.addMarker(new MarkerOptions().position(latLngLibrary).title(companyName));
                factoryPointLat = latLng.latitude;
                factoryPointLong = latLng.longitude;
            }
        });

        buttonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (factoryPointLat == 0) {
                    Toast.makeText(FormMapActivity.this, "请选择工厂位置", Toast.LENGTH_SHORT).show();
                    return;
                }

                SharedPreferences sharedPreferences = getSharedPreferences("account",MODE_PRIVATE);
                email = sharedPreferences.getString("email", "");

                if (reset) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("email", email);
                        jsonObject.put("mode", 2);
                        jsonObject.put("oldName", oldName);
                        jsonObject.put("newName", factoryName);
                        jsonObject.put("fPhone", factoryPhone);
                        jsonObject.put("fManager", factoryCharge);
                        jsonObject.put("fWater", Integer.parseInt(useWater));
                        jsonObject.put("fElectricity", Integer.parseInt(useElectricity));
                        jsonObject.put("fGas", Integer.parseInt(useGas));
                        jsonObject.put("fHeat", Integer.parseInt(useHeat));
                        jsonObject.put("fLongitude", factoryPointLong);
                        jsonObject.put("fLatitude", factoryPointLat);

                        new OceanUtil("resetFactory.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                            @Override
                            public void callback(String strResponse) {
                                response = strResponse;
                                Message message = new Message();
                                message.what = 2;
                                handler.sendMessage(message);
                            }
                        }).postInfo();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("email", email);
                        jsonObject.put("fName", factoryName);
                        jsonObject.put("fPhone", factoryPhone);
                        jsonObject.put("fManager", factoryCharge);
                        jsonObject.put("fWater", Integer.parseInt(useWater));
                        jsonObject.put("fElectricity", Integer.parseInt(useElectricity));
                        jsonObject.put("fGas", Integer.parseInt(useGas));
                        jsonObject.put("fHeat", Integer.parseInt(useHeat));
                        jsonObject.put("fLongitude", factoryPointLong);
                        jsonObject.put("fLatitude", factoryPointLat);
                        jsonObject.put("mode", 2);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    new OceanUtil("factory.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                        @Override
                        public void callback(String strResponse) {
                            response = strResponse;
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }).postInfo();
                }


            }
        });

    }

    private void initViews() {
        mMapView = findViewById(R.id.formMap_map);
        buttonSubmit = findViewById(R.id.formMap_button_submit);

        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        companyPointLat = getIntent().getDoubleExtra("companyPointLat",0);
        companyPointLong = getIntent().getDoubleExtra("companyPointLong", 0);
        companyName = getIntent().getStringExtra("companyName");
        companyPhone = getIntent().getStringExtra("companyPhone");
        factoryName = getIntent().getStringExtra("newName");
        factoryPhone = getIntent().getStringExtra("fPhone");
        factoryCharge = getIntent().getStringExtra("fManager");
        useWater = getIntent().getStringExtra("useWater");
        useElectricity = getIntent().getStringExtra("useElectricity");
        useGas = getIntent().getStringExtra("useGas");
        useHeat = getIntent().getStringExtra("useHeat");
        reset = getIntent().getBooleanExtra("reset", false);

        if (reset) {
            oldName = getIntent().getStringExtra("oldName");
            buttonSubmit.setText("修改");

            factoryPointLat = getIntent().getDoubleExtra("oldLat", 0);
            factoryPointLong = getIntent().getDoubleExtra("oldLong", 0);
            LatLng latLng = new LatLng(factoryPointLat, factoryPointLong);
            factoryMarker = aMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(),R.drawable.ic_location))));
        }
    }

    @SuppressLint("HandlerLeak")
    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case 1:
                        if (response.contains("10011")) {
                            finish();
                        }
                        if (response.contains("-20011")) {
                            Toast.makeText(FormMapActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case 2:
                        if (response.contains("10022")) {
                            finish();
                        }
                        if (response.contains("-20022")) {
                            Toast.makeText(FormMapActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    default:
                        break;
                }
            }
        };
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

}
